//
//  WPReadingRankingCommentVC.m
//  wobingwoyi
//
//  Created by WGP on 2016/11/29.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPReadingRankingCommentVC.h"
#import "WPNewCommentCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "WPNewCommentModel.h"
#import "WPMRModel.h"
#import "WPCommentBtn.h"
#import "WPMinePlaceholderTextView.h"
#import "WPReadingRankingSubCommentVC.h"

@interface WPReadingRankingCommentVC ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>

@property(nonatomic,copy)NSString *url;
@property(nonatomic,strong)UIView *noCommentView;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,strong)UIView *textViewBgView;
@property(nonatomic,strong)WPMinePlaceholderTextView *textView;
@property(nonatomic,strong)UIButton *coverBtn;
@property(nonatomic,strong)UIButton *composeBtn;
@property(nonatomic,strong)UIButton *sendBtn;

@property(nonatomic,strong)NSMutableArray *models;

@property(nonatomic,assign)int indexPage;

@end

@implementation WPReadingRankingCommentVC

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self refreshData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self tableView];
    [self bottomView];
}

-(UITableView *)tableView
{
    if(_tableView == nil)
    {
        _tableView = [[UITableView alloc] init];
        _tableView.backgroundColor = GlobalBgColor;
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        [_tableView registerClass:[WPNewCommentCell class] forCellReuseIdentifier:@"WPNewCommentCell"];
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.view);
            make.bottom.equalTo(self.view).offset(-49);
        }];
        
        __weak typeof(self) weakself = self;
        MJRefreshNormalHeader *mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            //      刷新数据
            [weakself refreshData];
        }];
        _tableView.mj_header = mj_header;
        [mj_header setTitle:@"下拉可以刷新" forState:MJRefreshStateIdle];
        [mj_header setTitle:@"松开立即刷新" forState:MJRefreshStatePulling];
        [mj_header setTitle:@"正在刷新" forState:MJRefreshStateRefreshing];
        mj_header.stateLabel.textColor = GLobalFontColor;
        mj_header.lastUpdatedTimeLabel.textColor = GLobalFontColor;
        
        //    上拉刷新控件
        MJRefreshAutoFooter *mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            [weakself loadMoreData];
            [mj_footer endRefreshing];
        }];
        self.tableView.mj_footer = mj_footer;
        mj_footer.automaticallyRefresh = NO;
        mj_footer.automaticallyHidden = NO;
    }
    return _tableView;
}

-(UIView *)bottomView
{
    if (_bottomView == nil)
    {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_bottomView];
        
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self.view);
            make.top.equalTo(self.tableView.mas_bottom);
        }];
        
        UIImageView *lineView = [[UIImageView alloc] init];
        lineView.backgroundColor = GLobalLineColor;
        [_bottomView addSubview:lineView];
        
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(_bottomView);
            make.height.mas_equalTo(0.5);
        }];
        
        WPCommentBtn *commentBtn = [[WPCommentBtn alloc] init];
        [commentBtn setBackgroundImage:[UIImage imageNamed:@"reading_fieldBgImage"] forState:UIControlStateNormal];
        [commentBtn setTitle:@"写评论...." forState:UIControlStateNormal];
        commentBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
        [commentBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
        [commentBtn addTarget:self action:@selector(commentBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        commentBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.bottomView addSubview:commentBtn];
        
        [commentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.bottomView);
            make.left.equalTo(self.bottomView).offset(15);
            make.right.equalTo(self.bottomView).offset(-15);
            make.height.mas_equalTo(28);
        }];
    }
    return _bottomView;
}

-(UIView *)textViewBgView
{
    if (_textViewBgView == nil)
    {
        
        _textViewBgView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height, SCREEN_WIDTH, 145)];
        _textViewBgView.backgroundColor = GlobalBgColor;
        [self.view addSubview:_textViewBgView];
    }
    return _textViewBgView;
}

-(WPMinePlaceholderTextView *)textView
{
    if (_textView == nil)
    {
        _textView = [[WPMinePlaceholderTextView alloc] init];
        _textView.placeholder = @"有价值的评论将会被优先展示(400字以内)";
        _textView.font = [UIFont systemFontOfSize:14];
        _textView.textColor = GLobalFontColor;
        _textView.layer.cornerRadius = 4;
        _textView.layer.masksToBounds = YES;
        _textView.delegate = self;
        [self.textViewBgView addSubview:_textView];
        
        [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.equalTo(self.textViewBgView).offset(10);
            make.right.equalTo(self.textViewBgView).offset(-10);
            make.height.mas_equalTo(90);
        }];
    }
    return _textView;
}

-(UIButton *)sendBtn
{
    if (_sendBtn == nil)
    {
        _sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sendBtn setBackgroundImage:[UIImage imageNamed:@"reading_sendBtn_disable"] forState:UIControlStateDisabled];
        [_sendBtn setBackgroundImage:[UIImage imageNamed:@"reading_sendBtn_enable"] forState:UIControlStateNormal];
        _sendBtn.enabled = NO;
        [_sendBtn addTarget:self action:@selector(sendBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        [self.textViewBgView addSubview:_sendBtn];
        
        [_sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.textViewBgView).offset(-10);
            make.top.equalTo(self.textView.mas_bottom).offset(10);
        }];
    }
    return _sendBtn;
}

-(void)setModel:(WPMRModel *)model
{
    _model = model;
    
    self.url = @"appraise/findAppraise.do";
    NSDictionary *dict = @{@"recordId":@(self.model.id)};
    
    [self showWithStatus:@"正在加载"];
    
    [[WPNetWorkManager sharedNetWorkManager] POST:self.url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            NSArray *arr = responseDict[@"detail"];
            //有评论的时候
            if (arr.count)
            {
                //不满一页影藏底部刷新控件
                if (arr.count < 10)
                {
                    self.tableView.mj_footer.hidden = YES;
                }
                
                for (NSDictionary *dict in arr)
                {
                    WPNewCommentModel *model = [WPNewCommentModel yy_modelWithDictionary:dict];
                    [self.models addObject:model];
                }
                
                //评论页数置为1
                self.indexPage = 1;
                
                [self.tableView reloadData];
            }
            else
            {
                //展示没有评论的界面
                [self showNoCommentView];
            }
            
            [self dismiss];
        }
        else
        {
            [self dismiss];
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:@"加载失败"];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

-(void)showNoCommentView
{
    UIView *noCommentView = [UIView new];
    self.noCommentView = noCommentView;
    noCommentView.backgroundColor = RGB_SAME(245);
    noCommentView.frame = self.tableView.bounds;
    [self.view addSubview:noCommentView];
    
    UIImageView *noCommentImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"no_comment"]];
    [noCommentImageView sizeToFit];
    [noCommentView addSubview:noCommentImageView];
    
    [noCommentImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(noCommentView);
        make.top.equalTo(noCommentView).offset(85*kMoreDetailCaseScale);
    }];
    
    UILabel *noCommentLabel = [UILabel new];
    noCommentLabel.text = @"暂无其他评论";
    noCommentLabel.font = [UIFont systemFontOfSize:14];
    noCommentLabel.textColor = GloballightFontColor;
    [noCommentView addSubview:noCommentLabel];
    
    [noCommentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(noCommentView);
        make.top.equalTo(noCommentImageView.mas_bottom).offset(20*kMoreDetailCaseScale);
    }];
}

#pragma mark - tableView的数据源方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.models.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPNewCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WPNewCommentCell"];
    cell.model = self.models[indexPath.item];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:@"WPNewCommentCell" cacheByIndexPath:indexPath configuration:^(WPNewCommentCell *cell) {
        // 配置 cell 的数据源，和 "cellForRow" 干的事一致，比如：
        cell.model = self.models[indexPath.item];
    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPNewCommentModel *model = self.models[indexPath.item];
    
        WPReadingRankingSubCommentVC *vc = [WPReadingRankingSubCommentVC new];
        vc.recordId = self.model.id;
        vc.model = model;
        
        ZNBPanNavigationController *nav = [[ZNBPanNavigationController alloc] initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];

}

#pragma mark - 下拉上拉刷新
-(void)refreshData
{
    NSString *url = @"appraise/findAppraise.do";
    NSDictionary *dict = @{@"recordId":@(self.model.id),@"page":@(0)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
        
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            if ([responseObject[@"detail"] count])
            {
                self.tableView.hidden = NO;
                
                [self.models removeAllObjects];
                for (NSDictionary *dict in responseDict[@"detail"])
                {
                    WPNewCommentModel *model = [WPNewCommentModel yy_modelWithDictionary:dict];
                    [self.models addObject:model];
                }
                
                //不满一页就隐藏
                if (self.models.count < 10)
                {
                    self.tableView.mj_footer.hidden = YES;
                }
                else
                {
                    self.tableView.mj_footer.hidden = NO;
                }
                
                
                self.indexPage = 1;
                [self.tableView reloadData];
            }
            
            [self.tableView.mj_header endRefreshing];
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:@"加载失败"];
            }
            
            [self.tableView.mj_header endRefreshing];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
            [self showErrorInfoWithStatus:@"网络错误"];
            [self.tableView.mj_header endRefreshing];
  
    }];
    
}

-(void)loadMoreData
{
    NSString *url = @"appraise/findAppraise.do";
    NSDictionary *dict = @{@"recordId":@(self.model.id),@"page":@(self.indexPage)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
        
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            NSArray *arr = responseDict[@"detail"];
            if (arr.count)
            {
                
                for (NSDictionary *dict in arr)
                {
                    WPNewCommentModel *model = [WPNewCommentModel yy_modelWithDictionary:dict];
                    [self.models addObject:model];
                }
                
                //不满一页就隐藏
                if (arr.count < 10)
                {
                    self.tableView.mj_footer.hidden = YES;
                }
                else
                {
                    self.tableView.mj_footer.hidden = NO;
                }
                
                self.indexPage++;
                [self.tableView reloadData];
            }
            
            [self.tableView.mj_footer endRefreshing];
        }
        else
        {
            [self dismiss];
            
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:@"加载失败"];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
        [self.tableView.mj_footer endRefreshing];
    }];
    
}

#pragma mark - textView的代理方法
-(void)textViewDidChange:(UITextView *)textView
{
    if(textView.text.length)
    {
        self.sendBtn.enabled = YES;
    }
    else
    {
        self.sendBtn.enabled = NO;
    }
}

#pragma mark - 按钮的点击事件
-(void)commentBtnDidClick:(UIButton *)btn
{
    if (![WPUserAccountViewModel sharedInstance].userLogin)
    {
        [[WPUserAccountViewModel sharedInstance] loginTipWith:^{
            
            WPMineLoginVC *vc = [WPMineLoginVC new];
            [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
        }];
        return ;
    }
    
    //注册键盘监听
    NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
    //添加注册监听  self 监听键盘自动发出的UIKeyboardWillChangeFrameNotification通知，调用self的keyboardFrameChange:进行处理
    [center addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [center addObserver:self selector:@selector(keyboardHideFrameChange:) name:UIKeyboardWillHideNotification object:nil];
    
    [self.textView becomeFirstResponder];
}

//键盘监听处理方法
- (void) keyboardFrameChange:(NSNotification *)notice
{
    //1.获取动画时间
    CGFloat time=[notice.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect endRect=[notice.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat offset = 0;
    
    // 获得应用程序主窗口
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    offset = endRect.origin.y-SCREEN_HEIGHT-145;
    if(self.coverBtn == nil)
    {
        self.coverBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        self.coverBtn.backgroundColor = RGBA_COLOR(51, 51, 51, 0.5);
        [self.coverBtn addTarget:self action:@selector(coverBtnDidClick) forControlEvents:UIControlEventTouchDown];
        [window addSubview:self.coverBtn];
    }
    
    [UIView animateWithDuration:time animations:^{
        
        CGRect frame = self.coverBtn.frame;
        frame.size.height = SCREEN_HEIGHT+offset;
        self.coverBtn.frame = frame;
        
        self.textViewBgView.transform=CGAffineTransformMakeTranslation(0, offset);
    }];
}

-(void)keyboardHideFrameChange:(NSNotification *)notice
{
    //1.获取动画时间
    CGFloat time=[notice.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [self.coverBtn removeFromSuperview];
    self.coverBtn = nil;
    
    [UIView animateWithDuration:time animations:^{
        
        self.textViewBgView.transform=CGAffineTransformMakeTranslation(0, 0);
        
    } completion:^(BOOL finished) {
    }];
}

-(void)coverBtnDidClick
{
    [self.textView resignFirstResponder];
    
//    WPLog(@"移除通知");
    NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
    [center removeObserver:self];
}

-(void)sendBtnDidClick:(UIButton *)btn
{
    if (self.textView.text.length > 500)
    {
        [self showErrorInfoWithStatus:@"字数超出限制长度"];
        return ;
    }
    
    [self showWithStatus:@"正在发送"];
    
    NSString *url = @"appraise/addAppraise.do";
    NSString *content = self.textView.text;
    NSDictionary *value = @{@"content":content,@"recordId":@(self.model.id)};
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:value options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    //去除掉首尾的空白字符和换行字符
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSDictionary *dicts = @{@"json":jsonString};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dicts progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self dismiss];
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            self.noCommentView.hidden = YES;
            
            self.textView.text = nil;
            [self.textView resignFirstResponder];
            
            [self refreshData];
            
            NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
            [center removeObserver:self];
        }
        else
        {
            [self coverBtnDidClick];
            
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:@"评论失败"];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self dismiss];
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

//重新登陆的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        WPMineLoginVC *vc = [WPMineLoginVC new];
        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
    }
}

-(NSMutableArray *)models
{
    if(_models == nil)
    {
        _models = [NSMutableArray array];
    }
    return _models;
}

-(void)dealloc
{
    NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
    [center removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
